from typing import List, Optional, Dict, Any
from uuid import UUID
from datetime import datetime, timezone
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, delete
from models.remediations import RemediationItem, RemediationStatus
from schemas.remediations import RemediationCreate, RemediationUpdate, RemediationStatusUpdate
from log import log_info

async def get_remediation(db: AsyncSession, remediation_id: UUID) -> Optional[RemediationItem]:
    """获取特定整改项"""
    log_info(f"获取整改项 {remediation_id}", module="remediations")
    stmt = select(RemediationItem).where(RemediationItem.id == remediation_id)
    result = await db.execute(stmt)
    return result.scalar_one_or_none()

async def get_remediations_by_plan(
    db: AsyncSession, 
    plan_id: UUID, 
    skip: int = 0, 
    limit: int = 100,
    filters: Optional[Dict[str, Any]] = None
) -> List[RemediationItem]:
    """
    获取特定评估计划的所有整改项
    
    Args:
        db: 数据库会话
        plan_id: 评估计划ID
        skip: 跳过的记录数
        limit: 返回的最大记录数
        filters: 过滤条件
        
    Returns:
        整改项列表
    """
    log_info(f"获取计划 {plan_id} 的整改项列表", module="remediations")
    stmt = select(RemediationItem).where(RemediationItem.plan_id == plan_id)
    
    # 应用过滤条件
    if filters:
        if 'plan_id' in filters and filters['plan_id']:
            stmt = stmt.where(RemediationItem.plan_id == filters['plan_id'])
    
    # 应用分页
    stmt = stmt.offset(skip).limit(limit)
    
    result = await db.execute(stmt)
    return result.scalars().all()


async def create_remediation(db: AsyncSession, remediation: RemediationCreate) -> RemediationItem:
    """
    创建新的整改项
    
    Args:
        db: 数据库会话
        remediation: 整改项创建模型
        
    Returns:
        创建的整改项
    """
    log_info(f"创建新整改项", module="remediations")
    db_remediation = RemediationItem(**remediation.model_dump())
    db.add(db_remediation)
    await db.commit()
    await db.refresh(db_remediation)
    return db_remediation

async def update_remediation(
    db: AsyncSession, 
    db_remediation: RemediationItem, 
    remediation: RemediationUpdate
) -> RemediationItem:
    """
    更新现有整改项
    
    Args:
        db: 数据库会话
        db_remediation: 数据库中的整改项对象
        remediation: 整改项更新模型
        
    Returns:
        更新后的整改项
    """
    log_info(f"更新整改项: {db_remediation.id}", module="remediations")
    update_data = remediation.model_dump(exclude_unset=True)
    
    # 如果状态更新为已完成且未提供完成时间，则自动设置完成时间
    if 'status' in update_data and update_data['status'] == RemediationStatus.COMPLETED:
        if 'completion_date' not in update_data or not update_data['completion_date']:
            update_data['completion_date'] = datetime.utcnow()
    
    for field, value in update_data.items():
        setattr(db_remediation, field, value)
    
    db.add(db_remediation)
    await db.commit()
    await db.refresh(db_remediation)
    return db_remediation

async def update_remediation_status(
    db: AsyncSession, 
    remediation: RemediationItem
) -> RemediationItem:
    """
    更新整改项状态
    
    Args:
        db: 数据库会话
        remediation: 整改项
        
    Returns:
        更新后的整改项
    """
    log_info(f"更新整改项状态: {remediation.id}", module="remediations")
    db.add(remediation)
    await db.commit()
    await db.refresh(remediation)
    return remediation

async def delete_remediation(db: AsyncSession, db_remediation: RemediationItem) -> None:
    """
    删除整改项
    
    Args:
        db: 数据库会话
        db_remediation: 要删除的整改项
    """
    log_info(f"删除整改项: {db_remediation.id}", module="remediations")
    await db.delete(db_remediation)
    await db.commit()

async def delete_remediations(db: AsyncSession, remediation_ids: List[UUID]) -> None:
    """
    批量删除整改项
    
    Args:
        db: 数据库会话
        remediation_ids: 要删除的整改项ID列表
    """
    if not remediation_ids:
        return
    
    log_info(f"批量删除整改项: {len(remediation_ids)}个", module="remediations")
    stmt = delete(RemediationItem).where(RemediationItem.id.in_(remediation_ids))
    await db.execute(stmt)
    await db.commit()
